﻿#include "Bullet.h"
#include "BulletManager.h"
#include "cocostudio/CocoStudio.h"
using namespace cocos2d;
using namespace cocos2d::ui;
using namespace cocostudio::timeline;
Bullet::Bullet(BulletType bulletType, float bulletSpeed) :
	speed(bulletSpeed),
	bulletType(bulletType)
{

}

Bullet* Bullet::create(BulletType bulletType, float bulletSpeed) {
	Bullet* ret = new (std::nothrow) Bullet(bulletType, bulletSpeed);
	if (ret && ret->init()) {
		ret->autorelease();
		return ret;
	}
	CC_SAFE_DELETE(ret);
	return nullptr;
}

void Bullet::onEnter() {
	Widget::onEnter();
	if (bulletType == WeaponBullet) {
		root->stopAllActions();
		bullet->setVisible(true);
		bullet_boom->setVisible(false);
	}
	live = true;
	scheduleUpdate();
}

bool Bullet::init() {
	if (!Widget::init()) {
		return false;
	}
	initCSBFile();
	return true;
}

void Bullet::initCSBFile() {
	switch (bulletType) {
	case HeroBullet:
		root = CSLoader::createNode("scenes/game/ui/bullet.csb");
		break;
	case WeaponBullet:
		root = CSLoader::createNode("scenes/game/ui/weapon_bullet.csb");
		bullet_boom = dynamic_cast<Sprite*>(root->getChildByName("bullet_boom"));
		break;
	case EnemyBullet:
		break;
	case SkillBullet:
		break;
	default:
		break;
	}
	//加载csb文件
	this->addChild(root);
	bullet = dynamic_cast<Sprite*>(root->getChildByName("bullet"));
	bulletSize = bullet->getContentSize();
}

void Bullet::update(float dt) {
	if (!live) {//如果是死亡状态,则回收自身
		if (bulletType == WeaponBullet) {
			ActionTimeline* bulletDieAct = CSLoader::createTimeline("scenes/game/ui/weapon_bullet.csb");
			Sprite* bullet = dynamic_cast<Sprite*>(root->getChildByName("bullet"));
			bullet->setVisible(false);
			bullet_boom->setVisible(true);
			bulletDieAct->play("die", false);
			bulletDieAct->setAnimationEndCallFunc("die", [this]() {
				BulletManager::getInstance()->collection(this, bulletType);
			});
			root->runAction(bulletDieAct);
		} else {
			BulletManager::getInstance()->collection(this, bulletType);
		}
		unscheduleUpdate();
	}
	Vec2 pos = getPosition();//获取原先的坐标
	Vec2 dir = Vec2(0, 1);
	setPosition(pos + speed * dt * dir);
	float h = Director::getInstance()->getVisibleSize().height;
	float w = Director::getInstance()->getVisibleSize().width;
	float y = getPositionY();
	float x = getPositionX();
	//当超出屏幕时 
	if (y >= h + 50 || x <= -50 || x >= w + 50) {
		//将当前子弹从管理类中移除
		BulletManager::getInstance()->collection(this, bulletType);
		//removeFromParent();
	}
}

Rect Bullet::getBulletRect() {
	float x = convertToWorldSpace(root->getPosition()).x;
	float y = convertToWorldSpace(root->getPosition()).y;
	float width = bulletSize.width * 0.5;
	float height = bulletSize.height * 0.5;
	return Rect(x, y, width, height);
}